from typing import List

from ninja import Router
from ninja.pagination import paginate

from apps.manager.user_manager.schemas import PermissionGroupSchema, PermissionGrantSchema, \
    PermissionGroupResponseSchema
from apps.manager.user_manager.serializers import GroupSerializer
from apps.schemas import R
from models.models import PermissionGroup, Api, ManagerUser
from utils.auth import ManagerAuthBearer
from utils.decorators import handle_exception
from utils.paginations import MyPagination

permission_group_router = Router(tags=["权限分组管理"], auth=ManagerAuthBearer())


@permission_group_router.get("/groups", summary="获取权限分组列表", response=List[PermissionGroupResponseSchema])
@handle_exception("获取所有权限分组失败")
@paginate(MyPagination)
def get_permission_groups(request):
    """
    获取所有权限分组
    """
    groups = PermissionGroup.objects.all()
    return groups


@permission_group_router.get("/group/{group_id}", summary="获取权限分组详情")
@handle_exception("获取权限分组详情失败")
def get_permission_group(request, group_id):
    """
    获取权限分组详情
    """
    group = PermissionGroup.objects.get(id=group_id)
    return GroupSerializer(group).data


@permission_group_router.post("/group", summary="创建权限分组")
@handle_exception("创建权限分组失败")
def create_permission_group(request, data: PermissionGroupSchema):
    """
    创建权限分组
    """
    if PermissionGroup.objects.filter(name=data.name).exists():
        return R.fail("权限分组已存在")
    created = PermissionGroup.objects.create(**data.dict())
    created.api.add(*Api.objects.filter(user_default=True))
    return R.ok(msg="创建分组成功")


@permission_group_router.delete("/group/{group_id}", summary="删除权限分组")
@handle_exception("删除权限分组失败")
def delete_permission_group(request, group_id):
    """
    删除权限分组
    """
    group = PermissionGroup.objects.get(id=group_id)
    users = ManagerUser.objects.all()
    for user in users:
        if group.id is user.permission_group_id:
            return R.fail("该分组存在用户，禁止删除")
    group.delete()
    return R.ok(msg="删除成功")


@permission_group_router.post("/group/grant/{group_id}", summary="赋予分组接口权限")
@handle_exception("赋予分组接口权限失败")
def grant_permission(request, group_id: int, data: PermissionGrantSchema):
    """
    赋予分组接口权限
    """
    group = PermissionGroup.objects.get(id=group_id)
    if not isinstance(data.api, list) or not isinstance(data.menu, list):
        return R.fail("接口或菜单参数错误")
    user_default_api = list(Api.objects.filter(user_default=1).values_list('id', flat=True))
    group.api.set(data.api + user_default_api)
    group.menu.set(data.menu)
    return R.ok(msg="授权成功")
